
import java.sql.*;   // methods to process SQL commands

import javax.sql.*;  // ditto
//import org.postgresql.jdbc3.Jdbc3PoolingDataSource; // connection via JDBC to postgrSQL
import java.io.IOException;   // enable IOException objects & handling
import java.io.PrintWriter;   // enable PrintWriter (so can use .println())
import javax.servlet.http.*;  // provides servlet functionality
import javax.servlet.*;	      // ditto
import javax.*;


public class Login extends HttpServlet
{
	//private static DataSource ds;	// contains DB and connection data; see init()
	
	private final static int MAX_NUMBER_LOGIN_ATTEMPTS = 5;
	private final static String NO_HEADER = "no header";
	private final static String REDIRECT_TO_MAIN_PAGE_CODE 
		= "<meta http-equiv=\"REFRESH\" content=\"2;url=../Main_Page.jsp\">";
	private final static String REDIRECT_TO_LOGIN_CODE 
		= "<meta http-equiv=\"REFRESH\" content=\"3;url=../Login.jsp\">";
	private final static String REDIRECT_TO_CART_CODE_2 
		= "<meta http-equiv=\"REFRESH\" content=\"0;url=ShoppingCart\">";
	
	public static String checkLoginInfo(String email, String password, 
			HttpSession session, PrintWriter out)
    {	
		System.out.println("Checking login info with email=" + email + ", password=" + password);
		
		StringBuffer buf = new StringBuffer();	// StringBuffer is faster than String		
		// see the API doc at java.sun.com for details
		try
		{
			// connect to DB
			Class.forName("org.postgresql.Driver").newInstance();
			Connection connection = DriverManager.getConnection(
					"jdbc:postgresql://localhost/fabflixs", "testuser", "testpass");
			
			// get and build string of test DB's metadata
			Statement select = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
	                ResultSet.CONCUR_UPDATABLE);
			Statement select2 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
	                ResultSet.CONCUR_UPDATABLE);
			ResultSet resultPasswordMatch = select.executeQuery("Select * from customers WHERE email=\'" 
					+ email + "\' AND password=\'" + password + "\'");
			ResultSet resultEmailMatch = select2.executeQuery("Select * from customers WHERE email=\'" 
					+ email + "\'");
			
			boolean passwordMatch = resultPasswordMatch.last();
			boolean emailMatch = resultEmailMatch.last();		
			
			if (passwordMatch)
			{
				//do stuff to log the user in (with a session) and then go to shopping cart
				Bridge.logUserIn(email, session);
				//session.setAttribute(Constants.loggedInUserAttributeName, email);
				//buf.append( session.getAttribute(Constants.loggedInUserAttributeName) );
				return REDIRECT_TO_CART_CODE_2;
			}
			else
			{				
				Integer count = (Integer)session.getAttribute(Constants.loginAttemptAttributeName);
				
				if (count == null)
					session.setAttribute(Constants.loginAttemptAttributeName, new Integer(1) );
				else
					session.setAttribute(Constants.loginAttemptAttributeName, new Integer(count.intValue() + 1) );
				count = (Integer)session.getAttribute(Constants.loginAttemptAttributeName);
				
				if (count.intValue() == MAX_NUMBER_LOGIN_ATTEMPTS)
				{
					//clear the login attempt counter
					session.setAttribute(Constants.loginAttemptAttributeName, new Integer(0) );
					//send user back to the main page
					return REDIRECT_TO_MAIN_PAGE_CODE;
				}
				else
				{
					
					buf.append("<font color=\"red\"><h3>Error in login information. Please try again.</font></h3>\n");
					/*
					if (count == 1)
						buf.append("<h3>You've tried " + count + " time to log in. ");
					else
						buf.append("<h3>You've tried " + count + " times to log in. ");
					
					if (MAX_NUMBER_LOGIN_ATTEMPTS - count == 1)
						buf.append("You have <b>" + (MAX_NUMBER_LOGIN_ATTEMPTS - count) + "</b> try left.</h3>");
					else
						buf.append("You have <b>" + (MAX_NUMBER_LOGIN_ATTEMPTS - count) + "</b> tries left.</h3>");
					*/
					
					out.print("<html><head><title>Please Try To Log In Again...</title>"
							+ REDIRECT_TO_LOGIN_CODE + "</head>"
							+ "<body>" + buf.toString() + "</body>" 
							+"</html>");
					
					return NO_HEADER;
				}
			}			
		}
		catch (SQLException sqle)
		{
			buf.append("SQL exception occured: " + sqle.getMessage() );
		}
		catch (ClassNotFoundException cnfe)
		{
			buf.append("ClassNotFound exception occured");
		}
		catch (InstantiationException ie)
		{
			buf.append("Instantiation exception occured");
		}
		catch (IllegalAccessException iae)
		{
			buf.append("IllegalAccess exception occured");
		}
		
		// return buffered string of text
		return buf.toString();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		if (!Bridge.hasBeenToMainPage(request.getSession(), response.getWriter()))
		{
			return;
		}
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		HttpSession session = request.getSession();
						
		String body = "";
		String temp = checkLoginInfo( request.getParameter("login_email"), 
				request.getParameter("login_password"), session, out);
		
		if (temp.equals(REDIRECT_TO_MAIN_PAGE_CODE)) // we're out of login attempts
		{
			out.print("<html><head><title>Redirecting...</title>"
					+ REDIRECT_TO_MAIN_PAGE_CODE + "</head>"
					+ "<body>Too many login attempts. Returning to main page...</body>" 
					+"</html>");
		}
		else if (session.getAttribute(Constants.wantToGoToCartAttributeName) == null
				&& temp.equals(REDIRECT_TO_CART_CODE_2)) // we came from the main page
		{
			out.print("<html><head><title>Logging In...</title>"
					+ REDIRECT_TO_MAIN_PAGE_CODE + "</head>"
					+ "<body>Please wait...</body>" 
					+"</html>");
		}
		else if (temp.equals(REDIRECT_TO_CART_CODE_2)) // we tried to add to the cart
		{
			out.print("<html><head><title>Redirecting...</title>"
					+ REDIRECT_TO_CART_CODE_2 + "</head>"
					+ "<body> You are now logged in...</body>" 
					+"</html>");
		}
		else if (!temp.equals(NO_HEADER))
		{
			body += temp;
			out.print(Template.getTemplateHTML("Please Try Logging In Again", body, Constants.straightToCart,
					request.getSession() ));
		}		
		
	}
	
	// Upon init of servlet, open the moviedb database
	public void init() throws ServletException
	{
		
	}

	
}
